package com.qiaofang.applet.common.util;

import com.qiaofang.applet.common.dto.OrderDto;
import com.qiaofang.applet.common.dto.PageDataRequest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author QF2019
 */
public class PageUtil {

    /**
     * 获取分页对象
     *
     * @param request
     * @return
     */
    public static Pageable getPageable(PageDataRequest<?> request) {
        // 因为查询时页码是从0开始，但前端传过来的时候是从1开始，因此需要将实际查询的页码-1
        return PageRequest.of(request.getPageNo() > 0 ? request.getPageNo() - 1 : 0, request.getPageSize(), getSort(request.getOrderDtos()));
    }

    /**
     * 组装排序字段
     * @param orderDtos
     * @return
     */
    private static Sort getSort(List<OrderDto> orderDtos){
        List<Sort.Order> orderList = new ArrayList<>();
        if(CollectionUtils.isEmpty(orderDtos)){
            return Sort.by(orderList);
        }

        Sort.Direction direction;
        for(OrderDto orderDto : orderDtos){
            direction = Sort.Direction.fromString(orderDto.getDirection());
            if(direction == null){
                continue;
            }

            orderList.add(new Sort.Order(direction, orderDto.getProperty()));
        }
        return Sort.by(orderList);
    }

    /**
     * 开始分页
     * @param list
     * @param pageNum 页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static List startPage(List list, Integer pageNum,
                                 Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }

        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (!pageNum.equals(pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        List pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }
}
